﻿using GEPL.InterfaceLibrary;
using GEPL.StandardModulesLibrary.Models;
using GEPL.StandardModulesLibrary.Properties;
using GEPL.StandardModulesLibrary.ViewModels.Console;
using GEPL.StandardModulesLibrary.Views.Console;
using System;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using System.Text;

namespace GEPL.StandardModulesLibrary.Elements.Console
{
    [Serializable]
    public class ConsoleWriteElement : IElement
    {
        private readonly ConsoleWriteViewModel viewModel;

        public ConsoleWriteElement()
        {
            viewModel = new ConsoleWriteViewModel();
        }

        public ConsoleWriteElement(SerializationInfo info, StreamingContext context)
        {
            viewModel = new ConsoleWriteViewModel
            {
                WriteLine = info.GetBoolean(nameof(viewModel.WriteLine)),
                WriteList = (ObservableCollection<WriteItem>)info.GetValue(nameof(viewModel.WriteList), typeof(ObservableCollection<WriteItem>))
            };
        }

        public ElementType ElementType
        {
            get { return ElementType.NormalStatement; }
        }

        public ProjectType ProjectType
        {
            get { return ProjectType.Console; }
        }

        public string ElementName
        {
            get { return Resources.Names_Write; }
        }

        public object Data
        {
            get { return viewModel; }
        }

        public Type UserControlType
        {
            get { return typeof(ConsoleWriteView); }
        }

        public string GetScript()
        {
            var sb = new StringBuilder();
            sb.Append(viewModel.WriteLine ? "Console.WriteLine(" : "Console.Write(");

            foreach (var item in viewModel.WriteList)
            {
                sb.Append(item);
                sb.Append(',');
            }

            if (sb[sb.Length - 1] == ',')
                sb.Remove(sb.Length - 1, 1);
            sb.Append(')');

            return sb.ToString();
        }

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue(nameof(viewModel.WriteLine), viewModel.WriteLine);
            info.AddValue(nameof(viewModel.WriteList), viewModel.WriteList, typeof(ObservableCollection<WriteItem>));
        }
    }
}